package apis

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/config"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	config2 "github.com/go-admin-team/go-admin-core/sdk/config"
	"net/http"
	"strconv"
	"time"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/api/apis"
	"tuowei.com/app/teacher/service"
	dto2 "tuowei.com/app/teacher/service/dto"
	"tuowei.com/app/teacher/service/response"
	"tuowei.com/common/dto"
	"tuowei.com/pkg/util"
)

type UCenter struct {
	api.Api
	base
}

// 个人中心首页
func (u UCenter) Index(ctx *gin.Context) {
	teacherInfo := u.GetTeacherInfo(ctx)
	s := service.UCenter{}
	orderService := service.Order{}
	stuService := service.StudentsService{}
	err := u.MakeContext(ctx).MakeOrm().
		MakeService(&s.Service).MakeService(&orderService.Service).MakeService(&stuService.Service).
		Errors
	if err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	// 获取待跟进订单数量
	OrderNums := orderService.GetNums([]int{models.OfflineStatusFollowIng, models.OfflineStatusComplete}, teacherInfo.SysUser.UserId)
	var followOrderNum int
	var completeOrderNum int
	for _, v := range OrderNums {
		switch v.Status {
		case models.OfflineStatusFollowIng:
			followOrderNum = v.Total
		case models.OfflineStatusComplete:
			completeOrderNum = v.Total
		}
	}
	// 邀请学员的数量
	StuNums, amount := stuService.GetInvitedStudentsNums(teacherInfo.SysUser.UserId)
	rsp := response.CenterIndex{}
	rsp.FollowOrderCount = followOrderNum
	rsp.CompleteOrderCount = completeOrderNum
	rsp.Amount = amount
	rsp.InvitedStudentsCount = StuNums
	rsp.Phone = teacherInfo.Phone
	rsp.UserInfo = teacherInfo
	u.OK(rsp, "success")
}

func (u UCenter) MyInviteCode(ctx *gin.Context) {
	u.MakeContext(ctx)
	url := config.Get("H5_URL").String("")
	teacher := u.GetTeacherInfo(ctx)
	claim := &apis.InviteClaims{
		Id:             teacher.SysUser.UserId,
		StandardClaims: jwt.StandardClaims{},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)

	tokenStr, err := token.SignedString([]byte(config2.JwtConfig.Secret))
	if err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	bytes := util.MakeQrcodeBase64(url+"?type=teacher&token="+tokenStr, 256)
	u.OK(string(bytes), "success")
}

// 我邀请的学员
func (u UCenter) GetStudentsInvited(ctx *gin.Context) {
	s := service.UCenter{}
	req := dto.Pagination{}
	teacherInfo := u.GetTeacherInfo(ctx)
	err := u.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	lists := make([]models.SysStudent, 0)
	var count int64
	err = s.GetStudentsInvited(&lists, &count, req, teacherInfo.SysUser.UserId)
	if err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	arr := make([]response.GetStudentsInvitedResponse, len(lists))
	for k, v := range lists {
		var recentPay float64
		if len(v.Scores) > 0 {
			recentPay = v.Scores[0].ScoreChange * 100
		}
		arr[k] = response.GetStudentsInvitedResponse{
			Name:      v.Name,
			Id:        v.Id,
			CreatedAt: v.CreatedAt,
			TotalPay:  v.TotalPay,
			Cover:     v.Cover,
			IdCard:    v.IdCard,
			Label:     v.UserLabel,
			Phone:     v.Phone,
			RecentPay: recentPay,
		}
		arr[k].College = v.College.CollegesName
	}
	u.PageOK(arr, int(count), req.PageIndex, req.PageSize, "success")
}

// 个人中心我的学生
func (u UCenter) GetMyStudents(ctx *gin.Context) {
	s := service.UCenter{}
	teacherInfo := u.GetTeacherInfo(ctx)
	req := dto2.GetMyStudentsRequest{}
	err := u.MakeContext(ctx).MakeOrm().MakeService(&s.Service).Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	lists := make([]models.SysStudent, 0)
	var count int64
	err = s.GetMyStudents(&lists, &count, &req, teacherInfo.SysUser.UserId)
	if err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	arr := make([]response.GetStudentsInvitedResponse, len(lists))
	for k, v := range lists {
		arr[k] = response.GetStudentsInvitedResponse{
			Name:      v.Name,
			IdCard:    v.IdCard,
			Id:        v.Id,
			Cover:     v.Cover,
			Label:     v.UserType,
			CreatedAt: v.CreatedAt,
		}
		arr[k].College = v.College.CollegesName
	}
	u.PageOK(arr, int(count), req.PageIndex, req.PageSize, "success")
}

func (u UCenter) Cancellation(ctx *gin.Context) {
	err := u.MakeContext(ctx).MakeOrm().Errors
	if err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	teacherInfo := u.GetTeacherInfo(ctx)
	id := teacherInfo.SysUser.UserId
	err = u.Orm.Table(models.SysUser{}.TableName()).
		Where("user_id = ?", id).Update("is_auth_app_login", 0).Error
	if err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	u.OK(nil, "注销成功!")
}

func (u UCenter) PerformanceReport(ctx *gin.Context) {
	teacherInfo := u.GetTeacherInfo(ctx)
	s := service.UCenter{}
	orderService := service.Order{}
	studentService := service.StudentsService{}
	if err := u.MakeContext(ctx).MakeOrm().
		MakeService(&s.Service).MakeService(&orderService.Service).MakeService(&studentService.Service).
		Errors; err != nil {
		u.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	now := time.Now()
	// 当前月的
	currentCount, currentTotalPrice := orderService.StatisticsByTime(now.Year(), int(now.Month()), teacherInfo.SysUser.UserId)
	// 获取最近六个月的招生变化趋势
	tempTime := now.AddDate(0, -5, 0)
	sixMonthTime := time.Date(tempTime.Year(), tempTime.Month(), 1, 0, 0, 0, 0, time.Local)
	lists := studentService.StatisticsByTime(sixMonthTime, teacherInfo.SysUser.UserId)
	m := make(map[string]response.Trent)
	for i := 0; i < len(lists); i++ {
		month := int(lists[i].CreatedAt.Month())
		year := lists[i].CreatedAt.Year()
		keBie := lists[i].KeBie
		key := strconv.Itoa(year) + strconv.Itoa(month)
		if v, ok := m[key]; ok {

			if keBie == "文科" {
				v.WenKe++
			} else if keBie == "理科" {
				v.LiKe++
			}
			m[key] = v
		} else {
			t := response.Trent{
				WenKe: 0,
				LiKe:  0,
				Year:  year,
				Month: month,
			}
			if keBie == "文科" {
				t.WenKe++
			} else if keBie == "理科" {
				t.LiKe++
			}
			m[key] = t
		}
	}
	var trentLists response.TrentList
	trentLists = make([]response.Trent, 0)
	for k := range m {
		trentLists = append(trentLists, m[k])
	}
	trentLists = trentLists.Sort()

	// 本月邀请的学员
	var monthInvitedNums int
	monthInvitedNums = studentService.InvitedStudentsNum(now.Year(), now.Month(), teacherInfo.SysUser.UserId)
	// 总共邀请学员
	var invitedTotalNums int
	invitedTotalNums = studentService.InvitedTotalStudentsNum(teacherInfo.SysUser.UserId)
	// 总计邀请的付费学员
	var invitedPayedNums int
	invitedPayedNums = studentService.InvitedTotalPayedStudentsNum(teacherInfo.SysUser.UserId)
	rsp := response.StatisticResponse{
		OrderCount:       currentCount,
		OrderPriceSum:    currentTotalPrice,
		StudentsTrent:    trentLists,
		MonthInvitedNums: monthInvitedNums,
		InvitedTotalNums: invitedTotalNums,
		InvitedPayedNums: invitedPayedNums,
	}
	u.OK(rsp, "success")
}
